package com.liuyongsheng.teafile.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件存储工具类
 */
@Component
public class FileStorageUtil {

    @Value("${file.storage.root-path}")
    private String rootPath;

    @Value("${file.storage.use-uuid-naming:true}")
    private boolean useUuidNaming;

    /**
     * 生成文件名
     * @param originalFileName 原始文件名
     * @return 生成的文件名
     */
    private String generateFileName(String originalFileName) {
        if (useUuidNaming) {
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            return java.util.UUID.randomUUID().toString() + extension;
        }
        return originalFileName;
    }

    /**
     * 获取当前年月
     * @return 当前年月字符串
     */
    private String getCurrentYearMonth() {
        return java.time.format.DateTimeFormatter.ofPattern("yyyyMM").format(java.time.LocalDate.now());
    }

    /**
     * 存储文件
     * @param fileBytes 文件字节数组
     * @param originalFileName 原始文件名
     * @return 存储的文件路径
     * @throws IOException 文件存储异常
     */
    public String storeFile(byte[] fileBytes, String originalFileName) throws IOException {
        String fileName = generateFileName(originalFileName);
        String yearMonth = getCurrentYearMonth();
        return storeFileInDir(fileBytes, yearMonth, fileName);
    }

    /**
     * 存储PDF文件
     * @param fileBytes PDF文件字节数组
     * @param originalFileName 原始文件名
     * @return 存储的文件路径
     * @throws IOException 文件存储异常
     */
    public String storePdf(byte[] fileBytes, String originalFileName) throws IOException {
        String fileName = generateFileName(originalFileName);
        String yearMonth = getCurrentYearMonth();
        return storeFileInDir(fileBytes, yearMonth, fileName);
    }

    /**
     * 存储图片文件
     * @param fileBytes 图片文件字节数组
     * @param originalFileName 原始文件名
     * @return 存储的文件路径
     * @throws IOException 文件存储异常
     */
    public String storeImage(byte[] fileBytes, String originalFileName) throws IOException {
        String fileName = generateFileName(originalFileName);
        String yearMonth = getCurrentYearMonth();
        return storeFileInDir(fileBytes, yearMonth, fileName);
    }

    /**
     * 在指定目录存储文件
     * @param fileBytes 文件字节数组
     * @param yearMonth 年月目录
     * @param fileName 文件名
     * @return 存储的文件路径
     * @throws IOException 文件存储异常
     */
    private String storeFileInDir(byte[] fileBytes, String yearMonth, String fileName) throws IOException {
        Path storagePath = Paths.get(rootPath, yearMonth);
        if (!Files.exists(storagePath)) {
            Files.createDirectories(storagePath);
        }

        Path filePath = storagePath.resolve(fileName);
        Files.write(filePath, fileBytes);
        
        return filePath.toString();
    }

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${server.port}")
    private int port;

    @Value("${file.access.host}")
    private String fileAccessHost;

    /**
     * 获取文件访问URL
     * @param storedFilePath 存储的文件路径
     * @return 文件访问URL
     */
    public String getFileUrl(String storedFilePath) {
        String fileName = Paths.get(storedFilePath).getFileName().toString();
        String yearMonth = getCurrentYearMonth();
        return "http://" + fileAccessHost + ":" + port + contextPath + "/" + yearMonth + "/" + fileName;
    }

    /**
     * 获取PDF文件访问URL
     * @param storedFilePath 存储的文件路径
     * @return PDF文件访问URL
     */
    public String getPdfUrl(String storedFilePath) {
        String fileName = Paths.get(storedFilePath).getFileName().toString();
        String yearMonth = getCurrentYearMonth();
        return "http://" + fileAccessHost + ":" + port + contextPath + "/" + yearMonth + "/" + fileName;
    }

    /**
     * 获取图片文件访问URL
     * @param storedFilePath 存储的文件路径
     * @return 图片文件访问URL
     */
    public String getImageUrl(String storedFilePath) {
        String fileName = Paths.get(storedFilePath).getFileName().toString();
        String yearMonth = getCurrentYearMonth();
        return "http://" + fileAccessHost + ":" + port + contextPath + "/" + yearMonth + "/" + fileName;
    }

    /**
     * 根据文件URL获取文件路径
     * @param fileUrl 文件URL
     * @return 文件路径
     */
    private String getFilePathFromUrl(String fileUrl) {
        String[] parts = fileUrl.split("/");
        String yearMonth = parts[parts.length - 2];
        String fileName = parts[parts.length - 1];
        return Paths.get(rootPath, yearMonth, fileName).toString();
    }

    /**
     * 删除单个文件
     * @param fileUrl 文件URL
     * @return 是否删除成功
     */
    public boolean deleteFile(String fileUrl) {
        try {
            String filePath = getFilePathFromUrl(fileUrl);
            return Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 批量删除文件
     * @param fileUrls 文件URL数组
     * @return 删除结果Map，key为文件URL，value为是否删除成功
     */
    public Map<String, Boolean> deleteFiles(List<String> fileUrls) {
        Map<String, Boolean> result = new HashMap<>();
        for (String fileUrl : fileUrls) {
            result.put(fileUrl, deleteFile(fileUrl));
        }
        return result;
    }

}
